#!/usr/bin/env python
# -*- coding:utf-8 -*-

import urllib
import urllib2

# 通过抓包的方式获取的url，并不是浏览器上显示的url
# --------------------------------------------------------------------------------------------------------------------------------------------------------------
url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null"
# url = "http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"

# 完整的headers
# --------------------------------------------------------------------------------------------------------------------------------------------------------------
headers = {
    "Accept": "application/json, text/javascript, */*; q=0.01",
    "X-Requested-With": "XMLHttpRequest",
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36",
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
}

# 用户接口输入
key = raw_input("请输入需要翻译的文字:")

# 获取post数据并且拆分
# --------------------------------------------------------------------------------------------------------------------------------------------------------------
# i=python%0A&from=AUTO&to=AUTO&smartresult=dict&client=fanyideskweb&salt=1522806930621&sign=aa90e0f3c2838f6f67621241129df1f5&doctype=json&version=2.1&keyfrom=fanyi.web&action=FY_BY_REALTIME&typoResult=false
# i=python
# from=AUTO
# to=AUTO
# smartresult=dict
# client=fanyideskweb
# salt=1522806930621
# sign=aa90e0f3c2838f6f67621241129df1f5
# doctype=json
# version=2.1
# keyfrom=fanyi.web
# action=FY_BY_REALTIME
# typoResult=false


# 发送到web服务器的表单数据
# --------------------------------------------------------------------------------------------------------------------------------------------------------------
formdata = {
    "i": key,
    "from": "AUTO",
    "to": "AUTO",
    "smartresult": "dict",
    "client": "fanyideskweb",
    "salt": "1522806930621",
    "sign": "aa90e0f3c2838f6f67621241129df1f5",
    "doctype": "json",
    "version": "2.1",
    "keyfrom": "fanyi.web",
    "action": "FY_BY_REALTIME",
    "typoResult": "false",
}

# 经过urlencode转码
data = urllib.urlencode(formdata)
# 如果Request()方法里的data参数有值，那么这个请求就是POST,如果没有，就是Get
request = urllib2.Request(url, data=data, headers=headers)

print urllib2.urlopen(request).read()
